import Support from "./base/support";
// import Animation from "./base/animation";
// 
let support = new Support()
// let animation = new Animation()

var board = new Array();
var score = 0;
var topScore = 0;
var hasConflicted = new Array();
var direction = {
  left: 1,
  up: 2,
  down: 3,
  right: 4
};


// import Player     from './player/index'
// import Support  from '../js/base/support'
/**
 * 底层背景, 读取屏幕的宽高, 设置棋盘边长
 */
let context = canvas.getContext('2d')
var bgw = canvas.width
var bgh = canvas.height
console.log(bgw, bgh)
var bdsl = 0.92 * bgw




let startX //触摸时的坐标   
let startY
let x //滑动的距离   
let y
let aboveY = 0 // 设一个全局变量记录上一次内部块滑动的位置  

/**
 * 游戏主函数
 */
export default class Main {
  constructor() {

    this.backGround()

    // 维护当前requestAnimationFrame的id
    this.aniId = 0

    this.restart()
  }

  backGround() {
    context.fillStyle = '#F0F0F0'
    context.fillRect(0, 0, bgw, bgh)
    context.fillStyle = '#8F7A66'
    context.fillRect(0.05 * bgw, 50, 0.2 * bgw, 0.16 * bgw)
    context.fillStyle = '#BAAB9E'
    context.fillRect(0.3 * bgw, 50, 0.3 * bgw, 0.16 * bgw)
    context.fillStyle = '#F7921E'
    context.fillRect(0.65 * bgw, 50, 0.3 * bgw, 0.16 * bgw)
    context.fillStyle = 'white'
    context.font = "30px Arial"
    context.fillText("重玩", 0.07 * bgw, 50 + 0.1 * bgw);
    context.font = "20px Arial"
    context.fillText("最高分数", 0.35 * bgw, 50 + 0.06 * bgw);
    context.fillText("当前分数", 0.7 * bgw, 50 + 0.06 * bgw);

    // 棋盘背景
    context.fillStyle = '#BBADA0'
    context.fillRect(0.04 * bgw, 0.45 * bgw, bdsl, bdsl)
  }

  restart() {
    //初始化棋盘格
    this.init();
    //在随机两个格子生成数字
    this.generateOneNumber();
    this.generateOneNumber();
    this.updateBoardView();
    score = 0;

    // canvas.removeEventListener(
    //   'touchstart',
    //   this.touchHandler
    // )

    // this.bg       = new BackGround(ctx)
    // this.player   = new Player(ctx)
    // this.gameinfo = new GameInfo()
    // this.music    = new Music()

    // this.bindLoop     = this.loop.bind(this)
    this.hasEventBind = false

    // 清除上一局的动画
    // window.cancelAnimationFrame(this.aniId);

    // this.aniId = window.requestAnimationFrame(
    //   this.bindLoop,
    //   canvas
    // )
    // 监听滑动事件
    canvas.addEventListener('touchstart', this.touchStart.bind(this), false);
    canvas.addEventListener('touchmove', this.touchMove.bind(this), false);
    canvas.addEventListener('touchend', this.touchEnd.bind(this), false);
  }

  init() {
    for (var i = 0; i < 4; i++) {
      for (var j = 0; j < 4; j++) {
        context.fillStyle = '#CCC0B3'
        context.fillRect(support.getPostionLeft(i, j) + 0.03 * bgw, support.getPostionTop(i, j) + 0.44 * bgw, 0.214 * bdsl, 0.214 * bdsl)
      }
    }

    //初始化棋盘
    for (var i = 0; i < 4; i++) {
      board[i] = new Array();
      hasConflicted[i] = new Array();
      for (var j = 0; j < 4; j++) {
        board[i][j] = 0;
        hasConflicted[i][j] = false;
      }
    }
    console.log(board);
    //更新面板
    this.updateBoardView();
  }

  updateBoardView() {
    // context.clearRect(0.04*bgw, 0.45*bgw, bdsl, bdsl) //更新之前先删除元素
    // context.fillRect(0.04*bgw, 0.45*bgw, bdsl, bdsl)
    for (var i = 0; i < 4; i++) {
      for (var j = 0; j < 4; j++) {
        //重新生成16个矩形, 并添加到容器中
        var offScreenCanvas = wx.createCanvas()
        var offContext = offScreenCanvas.getContext('2d')

        if (board[i][j] == 0) {
          offContext.fillStyle = '#CCC0B3'
          offContext.fillRect(support.getPostionLeft(i, j) + 0.04 * bgw, support.getPostionTop(i, j) + 0.44 * bgw, 0.214 * bdsl, 0.214 * bdsl)
          // 绘制无字空图
          context.drawImage(offScreenCanvas, 0, 0)
        } else {
          //根据数字颜色设置器背景色
          offContext.fillStyle = support.getBackgroundColorByNum(board[i][j])
          offContext.fillRect(support.getPostionLeft(i, j) + 0.04 * bgw, support.getPostionTop(i, j) + 0.44 * bgw, 0.214 * bdsl, 0.214 * bdsl)
          //设置前景字颜色
          offContext.fillStyle = support.getPreColorByNum(board[i][j])
          //显示数字(文字)
          offContext.font = "18px Arial"
          offContext.fillText(support.getShowTextByNum(board[i][j]), support.getPostionLeft(i, j) + 0.05 * bgw, support.getPostionTop(i, j) + 0.55 * bgw);

          context.drawImage(offScreenCanvas, 0, 0)
          hasConflicted[i][j] = false;
        }
      }
    }
  }

  generateOneNumber() {
    if (support.isNoSpace(board)) {
      return false;
    }
    //随机一个位置
    var randx = parseInt(Math.floor(Math.random() * 4));
    var randy = parseInt(Math.floor(Math.random() * 4));
    //判断生成的坐标是否合理(无值,位置即可使用)
    while (true) {
      if (board[randx][randy] === 0)
        break;
      //若果该坐标存在了值,即不合理,继续生成随机一个位置
      randx = parseInt(Math.floor(Math.random() * 4));
      randy = parseInt(Math.floor(Math.random() * 4));
    }

    //随机一个数字
    var randNum = Math.random() < 0.4 ? 2 : 4;
    board[randx][randy] = randNum;
    showNumberWithAnimation(randx, randy, randNum);
    return true;
  }

  /**
   * 滑动处理 1, 左滑; 2, 上滑, 3, 右滑; 4, 下滑
   */
  slideDirection(numm) {
    switch (numm) {
      case 1: //left
        if (this.moveLeft()) {
          setTimeout(this.generateOneNumber, 210);
          setTimeout(this.isGameOver, 300);
        }
        break;
      case 2: //up
        if (this.moveUp()) {
          setTimeout(this.generateOneNumber, 210);
          setTimeout(this.isGameOver, 300);
        }
        break;
      case 3: //right
        if (this.moveRight()) {
          setTimeout(this.generateOneNumber, 210);
          setTimeout(this.isGameOver, 300);
        }
        break;
      case 4: //down
        if (this.moveDown()) {
          setTimeout(this.generateOneNumber, 210);
          setTimeout(this.isGameOver, 300);
        }
        break;
      default:
        break;
    }
  }

  moveLeft() {
    if (!support.canMove(board, direction.left))
      return false;
    //左移
    for (var i = 0; i < 4; i++) {
      for (var j = 1; j < 4; j++) {
        if (board[i][j] !== 0) {
          for (var k = 0; k < j; k++)
            //可以一次移动多个格子
            if (board[i][k] == 0 && support.noBlockHorizontal(i, k, j, board)) {
              //move
              // showMoveAnimation(i, j, i, k);
              board[i][k] = board[i][j];
              board[i][j] = 0;
              continue;
            } else if (board[i][k] == board[i][j] && support.noBlockHorizontal(i, k, j, board) && !hasConflicted[i][k]) {
            //move
            // showMoveAnimation(i, j, i, k);
            //add
            board[i][k] += board[i][j];
            board[i][j] = 0;
            // var element = $("#grid-cell-" + i + k);
            // anp(element, board[i][k])
            score += board[i][k];
            this.updateScore(score);
            // updateTopScore(score);
            continue;
          }
        }
      }
    }
    setTimeout(this.updateBoardView, 200);  //等待200在执行更新面板操作,避免动画效果被冲掉
    return true
  }

  moveRight() {
    if (!support.canMove(board, direction.right))
      return false;
    //右移
    for (var i = 3; i >= 0; i--) {
      for (var j = 2; j >= 0; j--) {
        //该位置不等于0即可进行移动
        if (board[i][j] != 0)
          for (var k = 3; k > j; k--) {
            //如果可以一次移动多个格子
            if (board[i][k] == 0 && support.noBlockHorizontal(i, j, k, board)) {
              //move
              // showMoveAnimation(i, j, i, k);
              board[i][k] = board[i][j];
              board[i][j] = 0;
              continue;
            } else if (board[i][k] == board[i][j] && support.noBlockHorizontal(i, j, k, board) && !hasConflicted[i][k]) {
              //move
              // showMoveAnimation(i, j, i, k);
              //add
              board[i][k] += board[i][j];
              board[i][j] = 0;
              score += board[i][k];
              // var element = $("#grid-cell-" + i + k);
              // anp(element, board[i][k])
              this.updateScore(score);
              // updateTopScore(score);
              continue;
            }
          }
      }
    }
    setTimeout(this.updateBoardView, 200);  //等待200在执行更新面板操作,避免动画效果被冲掉
    return true
  }

  /**
    先判断第一列*/
  moveUp() {
    if (!support.canMove(board, direction.up))
      return false;
    for (var i = 0; i < 4; i++) {
      for (var j = 1; j < 4; j++) {
        //该位置不为0即可进行移动
        if (board[j][i] != 0) {
          for (var k = 0; k < j; k++) {
            if (board[k][i] == 0 && support.noBlockVectal(i, k, j, board)) {
              //move
              // showMoveAnimation(j, i, k, i);
              board[k][i] = board[j][i];
              board[j][i] = 0;
              continue;
            } else if (board[k][i] == board[j][i] && support.noBlockVectal(i, k, j, board) && !hasConflicted[k][i]) {
              //move
              // showMoveAnimation(j, i, k, i);
              board[k][i] += board[j][i];
              board[j][i] = 0;
              score += board[k][i];
              // var element = $("#grid-cell-" + k + i);
              // anp(element, board[k][i])
              this.updateScore(score);
              continue;
            }
          }
        }
      }
    }
    setTimeout(this.updateBoardView, 200);  //等待200在执行更新面板操作,避免动画效果被冲掉
    return true
  }

  /**
    先判断第一列*/
  moveDown() {
    if (!support.canMove(board, direction.down))
      return false;
    for (var i = 3; i >= 0; i--) {
      for (var j = 2; j >= 0; j--) {
        //该位置不为0即可进行移动
        if (board[j][i] != 0) {
          for (var k = 3; k > j; k--) {
            if (board[k][i] == 0 && support.noBlockVectal(i, j, k, board)) {
              //move
              // showMoveAnimation(j, i, k, i);
              board[k][i] = board[j][i];
              board[j][i] = 0;
              continue;
            } else if (board[k][i] == board[j][i] && support.noBlockVectal(i, j, k, board) && !hasConflicted[k][i]) {
              //move
              // showMoveAnimation(j, i, k, i);
              board[k][i] += board[j][i];
              board[j][i] = 0;
              score += board[k][i];
              // var element = $("#grid-cell-" + k + i);
              // anp(element, board[k][i])
              this.updateScore(score);
              continue;
            }
          }
        }
      }
    }
    // this.updateBoardView()
    setTimeout(this.updateBoardView, 200); //等待200在执行更新面板操作,避免动画效果被冲掉
    return true
  }

  isGameOver() {
    if (support.isNoSpace(board) && !support.canMoveALL(board)) {
      this.gameOver();
    }
  }

  gameOver() {
    alert("游戏结束!");
  }

  touchStart(e) { //触摸开始
    e.preventDefault();
    var touch = e.touches[0];
    startX = touch.pageX; //刚触摸时的坐标
    startY = touch.pageY; //刚触摸时的坐标
  }

  touchMove(e) { //滑动
    e.preventDefault();
    var touch = e.touches[0];
    x = touch.pageX - startX; //滑动的距离
    y = touch.pageY - startY; //滑动的距离      
  }

  touchEnd(e) { //手指离开屏幕
    // console.log(x);
    // console.log(y);
    
    var xy = Math.abs(x) - Math.abs(y);
    var d = 0;
    if (xy > 0) {
      if (x >= 0) {
        d = 3;
      } else {
        d = 1;
      }
    } else {
      if (y >= 0) {
        d = 4;
      } else {
        d = 2;
      }
    }

    this.slideDirection(d);
  }


  /**
   * 
   * 更新最新分数和最高分数
   */
  updateScore(score) {
    // $("#score").text(score);
    if (topScore < score) {
      // $("#top_score").text(score);
      topScore = score;
      return true;
    } else {
      return true;
      // $("#top_score").text(topScore);
    }
  }

  // 游戏结束后的触摸事件处理逻辑
  // touchEventHandler(e) {
  //   e.preventDefault()

  //   let x = e.touches[0].clientX
  //   let y = e.touches[0].clientY

  //   let area = this.gameinfo.btnArea

  //   if (x >= area.startX &&
  //     x <= area.endX &&
  //     y >= area.startY &&
  //     y <= area.endY)
  //     this.restart()
  // }
}


/********************* animation */
function showNumberWithAnimation(randx, randy, randNum) {
  var offScreenCanvas = wx.createCanvas()
  var offContext = offScreenCanvas.getContext('2d')
  offContext.fillStyle = support.getBackgroundColorByNum(randNum)
  offContext.fillRect(support.getPostionLeft(randx, randy) + 0.03 * bgw, support.getPostionTop(randx, randy) + 0.44 * bgw, 0.22 * bdsl, 0.214 * bdsl)

  offContext.fillStyle = support.getPreColorByNum(randNum)
  offContext.font = "18px Arial"
  //显示数字
  offContext.fillText(support.getShowTextByNum(randNum), support.getPostionLeft(randx, randy) + 0.05 * bgw, support.getPostionTop(randx, randy) + 0.55 * bgw)

  context.drawImage(offScreenCanvas, 0, 0)
  // numberCell.animate({
  //   width: cellSideLength,
  //   height: cellSideLength,
  //   top: getPostionTop(randx, randy),
  //   left: getPostionLeft(randx, randy)
  // }, 100);
}